<?php

defined('RESPONSE_SUCCESS')    && die('请确定常量 RESPONSE_SUCCESS 在别处未定义' . __FILE__);
defined('RESPONSE_ERROR')      && die('请确定常量 RESPONSE_ERROR 在别处未定义' . __FILE__);
defined('RESPONSE_NEED_LOGIN') && die('请确定常量 RESPONSE_NEED_LOGIN 在别处未定义' . __FILE__);
define('RESPONSE_SUCCESS',    0);
define('RESPONSE_ERROR',      1);
define('RESPONSE_NEED_LOGIN', 2);

/**
 * UCLibAjaxResponse is an ajax response converter
 */
class UCLibAjaxResponse
{
	/**
	 * 将Ajax请求的返回值进行统一编码
	 * @param errno: 错误代码，0表示没有错误
	 * @param message: 错误描述
	 * @param data: ajax返回的数据
	 * @param output: 输出还是返回，默认为输出
	 */
	public static function convert($errno = 0, $message = null, $data = null, $output = true) {
		$response = array (
			'errno' => $errno,
			'msg' => $message,
			'data' => $data
		);

		$response = json_encode($response);
		if (isset($_REQUEST["_script_key"])) {
			$response = "snda.lib.data.scriptCallback(".$_REQUEST["_script_key"].",".$response.");";
		}
		if ($output) {
			echo $response;
			return true;
		} else {
			return $response;
		}
	}

	/**
	 * 等同于convert(RESPONSE_SUCCESS, null, $data);
	 */
	public static function convertData($data) {
		self::convert(RESPONSE_SUCCESS, null, $data);
	}

	/**
	 *  等同于convertError($errno, $message, null);
	 */
	public static function convertError($errno, $message) {
		self::convert($errno, $message);
	}

	/**
	 *  等同于convertError($errno, $message, null);
	 */
	public static function isAjaxRequest() {
		if (isset($_REQUEST["_script_key"])) return true;
		return isset($_SERVER['HTTP_X_REQUESTED_WITH'])?$_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest' : false;
	}
}